﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NetDimension.Weibo;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace weibowinform
{

    public partial class Form1 : Form
    {

        private NetDimension.Weibo.OAuth oauth;
   public      NetDimension.Weibo.Client Sina;
        public static string AUTHORIZE_URL;
        public const string CallbackUrl = "https://api.weibo.com/oauth2/default.html";
         public const string AppKey="3257942575";
              public const string passport ="cbwang505@hotmail.com";
              public const string password = "wcb110120";
              public static string codeout;
   #region 微博列表的模板
   const string htmlPattern = @"<!DOCTYPE html>
<html lang=""en"" xmlns=""http://www.w3.org/1999/xhtml"">
<head>
	<title></title>
	<style type=""text/css"">
		html, body {
			font-size: 12px;
			cursor: default;
			padding: 5px;
			margin: 0;
			font-family:微软雅黑,Tahoma;
		}

		div.status {
			padding-left: 60px;
			position: relative;
			margin-bottom: 10px;
			min-height:80px;
			_height:80px;
		}

			div.status p {
				margin: 0 0 5px 0;
				line-height: 1.5;
				padding: 0;
			}

				div.status p span.name {
					color: #369;
				}

				div.status p.status-content {
					color: #333;
				}

				div.status p.status-count {
					color:#999;
				}

			div.status .face {
				position: absolute;
				left: 0;
				top: 0;
			}

			div.status div.repost {
				border: solid 1px #ACD;
				background: #F0FAFF;
				padding: 10px 10px 0 10px;
			}

		div.repost p.repost-content {
			color: #666 !important;
		}
	</style>
</head>
<body>
<!--StatusesList-->
</body>
</html>";
   const string imageParttern = @"<img src=""{0}"" alt=""图片"" class=""inner-pic"" />";
   const string statusPattern = @"	<div class=""status"">
		<img src=""{0}"" alt=""{1}"" class=""face"" />
		<p class=""status-content""><span class=""name"">{1}</span>：{2}</p>
		{3}
		<p class=""status-count"">转发({4}) 评论({5})</p>
	</div>
";
   const string repostPattern = @"	<div class=""status"">
		<img src=""{0}"" alt=""{1}"" class=""face"" />
		<p class=""status-content""><span class=""name"">{1}</span>：{2}</p>
		<div class=""repost"">
			<p class=""repost-cotent""><span class=""name"">@{3}</span>：{4}</p>
			{5}
			<p class=""status-count"">转发({6}) 评论({7})</p>
		</div>
		<p class=""status-count"">转发({8}) 评论({9})</p>
	</div>
";
   #endregion
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            oauth = new OAuth("3257942575", "c9990e1d462e41daa44949cf2d64f9fc", "https://api.weibo.com/oauth2/default.html");
           // bool bl = oauth.ClientLogin("cbwang505@hotmail.com", "wcb110120");
               
               string authorizeUrl = oauth.GetAuthorizeURL();
              AUTHORIZE_URL = authorizeUrl;
               richTextBox1.Text += authorizeUrl.ToString();
               webBrowser1.Url =new Uri( authorizeUrl.ToString());
        
               //HttpWebRequest req = (HttpWebRequest)WebRequest.Create(authorizeUrl);
               //HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
               //richTextBox1.Text += resp.ResponseUri.ToString();
               //String stroe = new StreamReader(resp.GetResponseStream()).ReadToEnd();
               //richTextBox1.Text += stroe;
               //System.Diagnostics.Process.Start(authorizeUrl);
          //  richTextBox1.Text+=bl.ToString()+oauth.AccessToken.ToString();

        }

        private void button2_Click(object sender, EventArgs e)
        {

            CookieContainer MyCookieContainer = new CookieContainer();
            HttpWebRequest http = WebRequest.Create(AUTHORIZE_URL) as HttpWebRequest;
            http.Referer = AUTHORIZE_URL;
            http.Method = "POST";
            http.ContentType = "application/x-www-form-urlencoded";
            http.AllowAutoRedirect = true;
            http.KeepAlive = true;
            http.CookieContainer = MyCookieContainer;
            string postBody = string.Format("action=submit&withOfficalFlag=0&ticket=&isLoginSina=&response_type=token&regCallback=&redirect_uri={0}&client_id={1}&state=&from=&userId={2}&passwd={3}&display=js", Uri.EscapeDataString(string.IsNullOrEmpty(CallbackUrl) ? "" : CallbackUrl), Uri.EscapeDataString(AppKey), Uri.EscapeDataString(passport), Uri.EscapeDataString(password));
            byte[] postData = Encoding.Default.GetBytes(postBody);
            http.ContentLength = postData.Length;

            using (Stream request = http.GetRequestStream())
            {
                try
                {
                    request.Write(postData, 0, postData.Length);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    request.Close();
                }
            }
            string code = string.Empty;
            try
            {
                using (HttpWebResponse response = http.GetResponse() as HttpWebResponse)
                {
                    if (response != null)
                    {
                        string codeuri = response.ResponseUri.ToString();
                        codeout = codeuri.Substring(codeuri.IndexOf("code") + 5);
                        richTextBox1.Text += codeuri;
                      
                    }
                    response.Close();
                }
            }
            catch (System.Net.WebException)
            {
                throw;
            }

           // string codeuri = webBrowser1.Url.ToString();
           //// richTextBox1.Text += codeuri;
           // string codeout = codeuri.Substring(codeuri.IndexOf("code") + 5);
           richTextBox1.Text += "/n你获取到的code是"+codeout;
            try
            {
                AccessToken accessToken = oauth.GetAccessTokenByAuthorizationCode(codeout);
            }
            catch (WeiboException ex)
            {
                Console.WriteLine(ex.Message);
            }
            if (string.IsNullOrEmpty(oauth.AccessToken))
            {

                MessageBox.Show("AccessTokennullexception");

            }
           
            this.Sina = new NetDimension.Weibo.Client(oauth);
            StringBuilder statusBuilder = new StringBuilder();
            var json = Sina.API.Entity.Statuses.FriendsTimeline(count:20);
				if (json.Statuses != null)
				{
					foreach (var status in json.Statuses)
					{
						if (status.User == null)
							continue;

						if (status.RetweetedStatus != null && status.RetweetedStatus.User != null)
						{
							statusBuilder.AppendFormat(repostPattern,
								status.User.ProfileImageUrl,
								status.User.ScreenName,
								status.Text,
								status.RetweetedStatus.User.ScreenName,
								status.RetweetedStatus.Text,
								string.IsNullOrEmpty(status.RetweetedStatus.ThumbnailPictureUrl) ? "" :
								string.Format(imageParttern, status.RetweetedStatus.ThumbnailPictureUrl),
								status.RetweetedStatus.RepostsCount,
								status.RetweetedStatus.CommentsCount,
								status.RepostsCount, status.CommentsCount);

						}
						else
						{
							statusBuilder.AppendFormat(statusPattern,
								status.User.ProfileImageUrl,
								status.User.ScreenName,
								status.Text,
								string.IsNullOrEmpty(status.ThumbnailPictureUrl) ? "" :
								string.Format(imageParttern, status.ThumbnailPictureUrl),
								status.RepostsCount, status.CommentsCount);
						}

					}
				}

				var html = htmlPattern.Replace("<!--StatusesList-->", statusBuilder.ToString());
                webBrowser1.DocumentText = html;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string postmessage = richTextBox2.Text;

            try
            {
                Sina.API.Entity.Statuses.Update(postmessage, 0, 0, null);
                richTextBox1.Text += "发布成功请刷新";
            }
            catch (Exception ex)
            {
              
                    MessageBox.Show(this, ex.Message, "哟？！出错了!", MessageBoxButtons.OK, MessageBoxIcon.Information);
        

            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            StringBuilder statusBuilder = new StringBuilder();
            var json = Sina.API.Entity.Statuses.FriendsTimeline(count: 20);
            if (json.Statuses != null)
            {
                foreach (var status in json.Statuses)
                {
                    if (status.User == null)
                        continue;

                    if (status.RetweetedStatus != null && status.RetweetedStatus.User != null)
                    {
                        statusBuilder.AppendFormat(repostPattern,
                            status.User.ProfileImageUrl,
                            status.User.ScreenName,
                            status.Text,
                            status.RetweetedStatus.User.ScreenName,
                            status.RetweetedStatus.Text,
                            string.IsNullOrEmpty(status.RetweetedStatus.ThumbnailPictureUrl) ? "" :
                            string.Format(imageParttern, status.RetweetedStatus.ThumbnailPictureUrl),
                            status.RetweetedStatus.RepostsCount,
                            status.RetweetedStatus.CommentsCount,
                            status.RepostsCount, status.CommentsCount);

                    }
                    else
                    {
                        statusBuilder.AppendFormat(statusPattern,
                            status.User.ProfileImageUrl,
                            status.User.ScreenName,
                            status.Text,
                            string.IsNullOrEmpty(status.ThumbnailPictureUrl) ? "" :
                            string.Format(imageParttern, status.ThumbnailPictureUrl),
                            status.RepostsCount, status.CommentsCount);
                    }

                }
            }

            var html = htmlPattern.Replace("<!--StatusesList-->", statusBuilder.ToString());
            webBrowser1.DocumentText = html;
        }

        private void button5_Click(object sender, EventArgs e)
        {
           
            CookieContainer MyCookieContainer = new CookieContainer();
            HttpWebRequest http = WebRequest.Create(AUTHORIZE_URL) as HttpWebRequest;
            http.Referer = AUTHORIZE_URL;
            http.Method = "POST";
            http.ContentType = "application/x-www-form-urlencoded";
            http.AllowAutoRedirect = true;
            http.KeepAlive = true;
            http.CookieContainer = MyCookieContainer;
            string postBody = string.Format("action=submit&withOfficalFlag=0&ticket=&isLoginSina=&response_type=token&regCallback=&redirect_uri={0}&client_id={1}&state=&from=&userId={2}&passwd={3}&display=js", Uri.EscapeDataString(string.IsNullOrEmpty(CallbackUrl) ? "" : CallbackUrl), Uri.EscapeDataString(AppKey), Uri.EscapeDataString(passport), Uri.EscapeDataString(password));
            byte[] postData = Encoding.Default.GetBytes(postBody);
            http.ContentLength = postData.Length;

            using (Stream request = http.GetRequestStream())
            {
                try
                {
                    request.Write(postData, 0, postData.Length);
                }
                catch
                {
                    throw;
                }
                finally
                {
                    request.Close();
                }
            }
            string code = string.Empty;
            try
            {
                using (HttpWebResponse response = http.GetResponse() as HttpWebResponse)
                {
                    if (response != null)
                    {
                      string    codeuri=response.ResponseUri.ToString();
                         string codeout = codeuri.Substring(codeuri.IndexOf("code") + 5);
                       richTextBox1.Text+=codeuri;
                    //    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    //    {
                    //        try
                    //        {
                    //            var html = reader.ReadToEnd();
                    //            var pattern1 = @"\{""access_token"":""(?<token>.{0,32})"",""remind_in"":""(?<remind>\d+)"",""expires_in"":(?<expires>\d+),""uid"":""(?<uid>\d+)""\}";
                    //            var pattern2 = @"\{""access_token"":""(?<token>.{0,32})"",""remind_in"":""(?<remind>\d+)"",""expires_in"":(?<expires>\d+),""refresh_token"":""(?<refreshtoken>.{0,32})"",""uid"":""(?<uid>\d+)""\}";
                    //            if (!string.IsNullOrEmpty(html) && (Regex.IsMatch(html, pattern1) || Regex.IsMatch(html, pattern2)))
                    //            {
                    //                var group = Regex.IsMatch(html, "refresh_token") ? Regex.Match(html, pattern2) : Regex.Match(html, pattern1);

                    //              string  AccessToken1 = group.Groups["token"].Value;
                    //                //if (token != null)
                    //                //{
                    //                //    token.ExpiresIn = Convert.ToInt32(group.Groups["expires"].Value);
                    //                //    token.Token = group.Groups["token"].Value;
                    //                //    token.UID = group.Groups["uid"].Value;
                    //                //}
                    //                result = true;
                    //            }
                    //        }
                    //        catch { }
                    //        finally
                    //        {
                    //            reader.Close();
                    //        }
                    //    }
                    }
                    response.Close();
                }
            }
            catch (System.Net.WebException)
            {
                throw;
            }

         

        }
    }
}
